import sys
import os
# 确保能够正确导入database模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy.orm import Session
from database.db import get_db, engine, Base
from models import FlightRoute, Drone, User
import math

# 辅助函数：计算航线距离
def calculate_route_distance(waypoints):
    """计算航线总距离"""
    total_distance = 0.0
    
    for i in range(1, len(waypoints)):
        wp1 = waypoints[i-1]
        wp2 = waypoints[i]
        
        # 计算两点之间的欧氏距离
        distance = math.sqrt(
            (wp2['lat'] - wp1['lat']) ** 2 +
            (wp2['lng'] - wp1['lng']) ** 2 +
            (wp2['alt'] - wp1['alt']) ** 2
        )
        total_distance += distance
    
    # 转换为千米并四舍五入到2位小数
    return round(total_distance * 111.32, 2)  # 简化的地球半径近似转换

# 定义5个默认航线的配置
default_routes = [
    {
        "name": "城市巡逻航线1",
        "description": "城市中心区域巡逻航线",
        "waypoints": [
            {"lat": 34.3442, "lng": 108.9074, "alt": 100},
            {"lat": 34.3542, "lng": 108.9174, "alt": 100},
            {"lat": 34.3542, "lng": 108.9274, "alt": 100},
            {"lat": 34.3442, "lng": 108.9274, "alt": 100},
            {"lat": 34.3442, "lng": 108.9074, "alt": 100}
        ],
        "estimated_time": 30
    },
    {
        "name": "农田监测航线",
        "description": "农作物生长情况监测航线",
        "waypoints": [
            {"lat": 34.2942, "lng": 108.8574, "alt": 80},
            {"lat": 34.2942, "lng": 108.8874, "alt": 80},
            {"lat": 34.2742, "lng": 108.8874, "alt": 80},
            {"lat": 34.2742, "lng": 108.8574, "alt": 80},
            {"lat": 34.2942, "lng": 108.8574, "alt": 80}
        ],
        "estimated_time": 25
    },
    {
        "name": "城市边缘巡查航线",
        "description": "城市边缘地区巡查航线",
        "waypoints": [
            {"lat": 34.3942, "lng": 109.0074, "alt": 120},
            {"lat": 34.4042, "lng": 109.0274, "alt": 120},
            {"lat": 34.4142, "lng": 109.0374, "alt": 120},
            {"lat": 34.4242, "lng": 109.0274, "alt": 120},
            {"lat": 34.4142, "lng": 109.0174, "alt": 120},
            {"lat": 34.3942, "lng": 109.0074, "alt": 120}
        ],
        "estimated_time": 40
    },
    {
        "name": "工业园区巡检航线",
        "description": "工业园区设备和安全巡检航线",
        "waypoints": [
            {"lat": 34.3642, "lng": 108.8274, "alt": 90},
            {"lat": 34.3742, "lng": 108.8374, "alt": 90},
            {"lat": 34.3742, "lng": 108.8474, "alt": 90},
            {"lat": 34.3642, "lng": 108.8474, "alt": 90},
            {"lat": 34.3542, "lng": 108.8374, "alt": 90},
            {"lat": 34.3642, "lng": 108.8274, "alt": 90}
        ],
        "estimated_time": 35
    },
    {
        "name": "应急救援演练航线",
        "description": "模拟应急救援场景的演练航线",
        "waypoints": [
            {"lat": 34.3242, "lng": 108.9574, "alt": 150},
            {"lat": 34.3342, "lng": 108.9674, "alt": 150},
            {"lat": 34.3442, "lng": 108.9574, "alt": 150},
            {"lat": 34.3342, "lng": 108.9474, "alt": 150},
            {"lat": 34.3242, "lng": 108.9574, "alt": 150}
        ],
        "estimated_time": 20
    }
]

def init_routes():
    """初始化默认航线数据"""
    print("开始初始化航线数据...")
    # 创建数据库会话
    db = next(get_db())
    
    try:
        # 获取无人机数量
        total_drones = db.query(Drone).count()
        available_drones = db.query(Drone).filter(Drone.status == "available").count()
        print(f"数据库中的无人机: 总共 {total_drones} 个, 可用 {available_drones} 个")
        
        # 获取第一个可用的无人机（如果有）
        drone = db.query(Drone).filter(Drone.status == "available").first()
        drone_id = drone.id if drone else None
        print(f"选择的无人机ID: {drone_id}")
        
        # 获取用户数量
        total_users = db.query(User).count()
        print(f"数据库中的用户数量: {total_users}")
        
        # 获取第一个用户作为创建者
        user = db.query(User).first()
        created_by = user.id if user else None
        print(f"选择的用户ID: {created_by}")
        
        # 检查现有航线数量
        existing_routes_count = db.query(FlightRoute).count()
        print(f"现有航线数量: {existing_routes_count}")
        
        # 删除所有现有航线
        if existing_routes_count > 0:
            print("删除所有现有航线...")
            db.query(FlightRoute).delete()
            db.commit()
            print("所有现有航线已删除")
        
        # 添加默认航线
        added_count = 0
        for route_data in default_routes:
            # 检查航线是否已存在
            existing_route = db.query(FlightRoute).filter(FlightRoute.name == route_data["name"]).first()
            if not existing_route:
                # 计算航线距离
                distance = calculate_route_distance(route_data["waypoints"])
                print(f"计算航线 '{route_data['name']}' 距离: {distance} 千米")
                
                # 创建新航线，只使用模型中实际存在的字段
                print(f"创建新航线: {route_data['name']}, 创建者ID: {created_by}")
                new_route = FlightRoute(
                    name=route_data["name"],
                    description=route_data["description"],
                    waypoints=route_data["waypoints"],
                    distance=distance,
                    is_active=True,
                    created_by=created_by
                )
                db.add(new_route)
                db.flush()  # 获取新航线的ID
                
                added_count += 1
                print(f"已添加默认航线: {route_data['name']}")
            else:
                print(f"航线已存在: {route_data['name']}")
        
        # 提交所有更改
        db.commit()
        print(f"默认航线数据初始化完成，成功添加 {added_count} 条航线")
        
        # 验证添加结果
        final_routes_count = db.query(FlightRoute).count()
        print(f"提交后航线总数量: {final_routes_count}")
    
    except Exception as e:
        print(f"初始化默认航线数据时出错: {str(e)}")
        import traceback
        traceback.print_exc()
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    # 确保表已创建
    Base.metadata.create_all(bind=engine)
    # 初始化航线数据
    init_routes()